import React, { useState } from 'react';
import { ProFormText, StepsForm } from '@ant-design/pro-form';
import { Button, Col, Form, Modal, Row } from 'antd';
import { FormattedMessage, useIntl } from 'umi';
import ShowAppTypeModal from './ShowAppTypeModal';
import ShowHostsListModal from './ShowHostsListModal';
import { SelectOutlined } from '@ant-design/icons';

// 定义value的类型，
export type FormValueType = {
  target?: string;
  template?: string;
  type?: string;
  time?: string;
  frequency?: string;
} & Partial<API.AppsInfoListItem>;

export type WizardModalProps = {
  // onCancel: (flag?: boolean, formVals?: FormValueType) => void;
  // 抽屉组件props里只有onClose 没有onCancle
  onCancel: () => void;
  onFinish: (values: API.AppsInfoListItem) => Promise<boolean>;
  onVisibleChange: (visible: boolean) => void;
  appWizardModalVisible: boolean;
  values: Partial<API.AppsInfoListItem>;
};

const AppWizardModal: React.FC<WizardModalProps> = (props) => {
  const intl = useIntl();

  // 操作 app的 type/solution/version 这三个值都是从子组件 ShowAppTypeModal选择而来
  const [appType, handleAppType] = useState<string>();
  const [appSolution, handleAppSolution] = useState<string>();
  const [appVersion, handleAppVersion] = useState<string>();

  // 操作 host的 hostname/ip/这两个值都是从子组件 ShowHostInfoModal选择而来
  const [hostname, handleHostname] = useState<string>();
  const [ip, handleIP] = useState<string>();

  // 显示应用模版列表modal
  const [showAppTypeModal, handleShowAppTypeModal] = useState<boolean>(false);
  const [showHostListModal, handleShowHostListModal] = useState<boolean>(false);

  return (
    <>
      {/* 如果想在表单之间(比如：把ShowAppTypeModal里面查询的相关应用模版的的数据回写到和 AddAppWizard里面去)
            现象: 查到的相关应用模版的的数据可以显示在AddAppWizard的StepForm里面，但是提交的时候，这些值就获取不到
            解决方法: 
            1. 增加 Form.Provider 去把关联的 form 包住
            2. 通过 onFormFinish 方法，侦测到某个form提交的时候去set一下value就可以了 */}
      <Form.Provider
        onFormFinish={(name, { values, forms }) => {
          if (name === 'step1') {
            console.log('In Step 1,Event=Form.Provider.onFormFinish, values=', values);
            const { step1 } = forms;
            step1.setFieldsValue({ apptype: appType });
            step1.setFieldsValue({ solution: appSolution });
            step1.setFieldsValue({ version: appVersion });
          }
          // 观察一下到其他step的状态
          if (name === 'step2') {
            console.log('In Step 2, Event=Form.Provider.onFormFinish, values=', values);
          }
          if (name === 'step3') {
            console.log('In Step 3, Event=Form.Provider.onFormFinish, values=', values);
            const { step3 } = forms;
            step3.setFieldsValue({ hostname: hostname });
            step3.setFieldsValue({ ip: ip });
          }
        }}
      >
        <StepsForm
          stepsProps={{
            size: 'small',
          }}
          stepsFormRender={(dom, submitter) => {
            return (
              <Modal
                width={800}
                bodyStyle={{
                  padding: '20px 20px 20px',
                }}
                destroyOnClose
                title={
                  props.values.id === undefined
                    ? intl.formatMessage({
                      id: 'pages.showAppWizard.add.title',
                      defaultMessage: '添加应用',
                    })
                    : intl.formatMessage({
                      id: 'pages.showAppWizard.update.title',
                      defaultMessage: '更新应用',
                    })
                }
                visible={props.appWizardModalVisible}
                footer={submitter}
                onCancel={() => {
                  props.onCancel();
                }}
              >
                {dom}
              </Modal>
            );
          }}
          onFinish={props.onFinish}
        >
          <StepsForm.StepForm
            title={intl.formatMessage({
              id: 'pages.showAppWizard.chooseTemplate.title',
              defaultMessage: '选择应用模版',
            })}
            name="step1"
            initialValues={{
              id: props.values.id,
              app_name: props.values.app_name,
              apptype: props.values.apptype,
              solution: props.values.solution,
              version: props.values.version,
            }}
          >
            <Row justify="space-between">
              {props.values.id === undefined ? (
                <Col span={6}>
                  <ProFormText
                    width="sm"
                    name="app_name"
                    label={
                      <FormattedMessage
                        id="pages.listAppsInfoTable.app_name"
                        defaultMessage="app_name"
                      />
                    }
                    placeholder="请输入应用名称"
                    rules={[
                      {
                        required: true,
                        message: (
                          <FormattedMessage
                            id="pages.searchTable.ruleName"
                            defaultMessage="Rule name is required"
                          />
                        ),
                      },
                    ]}
                  />
                </Col>
              ) : (
                <Col span={6}>
                  <ProFormText
                    width="sm"
                    name="app_name"
                    label={
                      <FormattedMessage
                        id="pages.listAppsInfoTable.app_name"
                        defaultMessage="app_name"
                      />
                    }
                    placeholder="请输入应用名称"
                    disabled
                    rules={[
                      {
                        required: true,
                        message: (
                          <FormattedMessage
                            id="pages.searchTable.ruleName"
                            defaultMessage="Rule name is required"
                          />
                        ),
                      },
                    ]}
                  />
                </Col>
              )}
              {/* 如果values为空表示时候为新建app，不展示app的id，否则是update，展示app的id*/}
              {props.values.id === undefined ? (
                <Col span={6}></Col>
              ) : (
                <Col span={6}>
                  <ProFormText
                    width="sm"
                    name="id"
                    label={<FormattedMessage id="pages.listAppsInfoTable.id" defaultMessage="id" />}
                    disabled
                  />
                </Col>
              )}
              <Col span={6}></Col>
            </Row>

            <Row>
              <Col span={6}>
                <Button
                  type="primary"
                  key="primary"
                  onClick={() => {
                    handleShowAppTypeModal(true);
                  }}
                >
                  <SelectOutlined />{' '}
                  <FormattedMessage
                    id="pages.showAppWizard.chooseTemplate.choose"
                    defaultMessage="Choose"
                  />
                </Button>
              </Col>
            </Row>
            <p></p>
            <Row justify="space-between">
              <Col span={6}>
                <ProFormText
                  width="sm"
                  name="apptype"
                  label={
                    <FormattedMessage
                      id="pages.listAppsInfoTable.apptype"
                      defaultMessage="apptype"
                    />
                  }
                  placeholder="应用类型"
                  fieldProps={{ value: appType }}
                  disabled
                />
              </Col>
              <Col span={6}>
                <ProFormText
                  name="solution"
                  width="sm"
                  label={
                    <FormattedMessage
                      id="pages.listAppsInfoTable.solution"
                      defaultMessage="Solution"
                    />
                  }
                  fieldProps={{ value: appSolution }}
                  placeholder="所属系统"
                  disabled
                />
              </Col>
              <Col span={6}>
                <ProFormText
                  width="sm"
                  name="version"
                  label={
                    <FormattedMessage
                      id="pages.listAppsInfoTable.version"
                      defaultMessage="Version"
                    />
                  }
                  placeholder="版本信息"
                  fieldProps={{ value: appVersion }}
                  disabled
                />
              </Col>
            </Row>
          </StepsForm.StepForm>

          <StepsForm.StepForm
            initialValues={{
              port: props.values.port || '8118',
              workdir: props.values.workdir,
              logdir: props.values.logdir,
              command: props.values.command,
            }}
            title={intl.formatMessage({
              id: 'pages.listAppsInfoTable.advanceInfoConfig',
              defaultMessage: '其他配置',
            })}
            name="step2"
          >
            <Row justify="start">
              <Col span={12}>
                <ProFormText
                  width="sm"
                  name="port"
                  label={
                    <FormattedMessage id="pages.listAppsInfoTable.port" defaultMessage="PORT" />
                  }
                  // validate
                  rules={[
                    {
                      required: true,
                      message: (
                        <FormattedMessage
                          id="pages.searchTable.ruleName"
                          defaultMessage="Rule name is required"
                        />
                      ),
                    },
                    {
                      // pattern: /^([1-9]|[1-9]\d{1,3}|[1-6][0-5][0-5][0-3][0-5])$/,
                      // /^(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\:([0-9]|[1-9]\d{1,3}|[1-5]\d{4}|6[0-5]{2}[0-3][0-5])$/
                      pattern: /^([0-9]|[1-9]\d{1,3}|[1-5]\d{4}|6[0-5]{2}[0-3][0-5])$/,
                      message: (
                        <FormattedMessage
                          id="pages.listAppsInfoTable.ruleport"
                          defaultMessage="Port must from 1-65535"
                        />
                      ),
                    },
                  ]}
                  placeholder="请输入端口号"
                />
              </Col>
            </Row>
            <Row justify="start">
              <Col span={12}>
                <ProFormText
                  width="sm"
                  name="command"
                  label={
                    <FormattedMessage
                      id="pages.listAppsInfoTable.command"
                      defaultMessage="command"
                    />
                  }
                  // validate
                  rules={[
                    {
                      required: true,
                      message: (
                        <FormattedMessage
                          id="pages.searchTable.ruleName"
                          defaultMessage="Rule name is required"
                        />
                      ),
                    },
                  ]}
                  placeholder="请输入启动命令"
                />
              </Col>
            </Row>
            <Row justify="start">
              <Col span={12}>
                <ProFormText
                  width="md"
                  name="workdir"
                  label={
                    <FormattedMessage
                      id="pages.listAppsInfoTable.workdir"
                      defaultMessage="workdir"
                    />
                  }
                  // validate
                  rules={[
                    {
                      required: true,
                      message: (
                        <FormattedMessage
                          id="pages.searchTable.ruleName"
                          defaultMessage="Rule name is required"
                        />
                      ),
                    },
                  ]}
                  placeholder="请输入安装目录"
                />
              </Col>
            </Row>
            <Row justify="start">
              <Col span={12}>
                <ProFormText
                  width="md"
                  name="logdir"
                  label={
                    <FormattedMessage id="pages.listAppsInfoTable.logdir" defaultMessage="logdir" />
                  }
                  // validate
                  rules={[
                    {
                      required: true,
                      message: (
                        <FormattedMessage
                          id="pages.searchTable.ruleName"
                          defaultMessage="Rule name is required"
                        />
                      ),
                    },
                  ]}
                  placeholder="请输入日志目录"
                />
              </Col>
            </Row>
          </StepsForm.StepForm>
          <StepsForm.StepForm
            initialValues={{
              hostname: props.values.hostname,
              ip: props.values.ip,
            }}
            title={intl.formatMessage({
              id: 'pages.listAppsInfoTable.bindHost',
              defaultMessage: '绑定主机',
            })}
            name="step3"
          >
            <Row>
              <Col span={12}>
                <Button
                  type="primary"
                  key="primary"
                  onClick={() => {
                    handleShowHostListModal(true);
                  }}
                >
                  <SelectOutlined />{' '}
                  <FormattedMessage
                    id="pages.showAppWizard.chooseHost.title"
                    defaultMessage="Choose Host"
                  />
                </Button>
              </Col>
            </Row>
            <p></p>
            <Row justify="space-between">
              <Col span={12}>
                <ProFormText
                  name="hostname"
                  width="sm"
                  label={
                    <FormattedMessage
                      id="pages.listHostsInfoTable.hostname"
                      defaultMessage="Hostname"
                    />
                  }
                  fieldProps={{ value: hostname }}
                  placeholder="所属系统"
                  disabled
                />
              </Col>
              <Col span={12}>
                <ProFormText
                  width="sm"
                  name="ip"
                  label={<FormattedMessage id="pages.listHostsInfoTable.ip" defaultMessage="IP" />}
                  placeholder="版本信息"
                  fieldProps={{ value: ip }}
                  disabled
                />
              </Col>
            </Row>
          </StepsForm.StepForm>
        </StepsForm>
        <ShowAppTypeModal
          onChoose={async (value) => {
            console.log('AddAppWizardForm 表单: Event=ShowAppTypeModal.onChoose,value =', value);
            handleShowAppTypeModal(false);
            handleAppType(value.apptype);
            handleAppVersion(value.version);
            handleAppSolution(value.solution);
          }}
          onVisibleChange={(visible) => {
            if (visible) {
              console.log('AddAppWizardForm 表单: Event=onVisibleChange -> 显示ShowAppTypeModal');
            } else {
              console.log('AddAppWizardForm 表单: Event=onVisibleChange -> 关闭ShowAppTypeModal');
            }
            handleShowAppTypeModal(visible);
          }}
          showAppTypeModalVisible={showAppTypeModal}
          onClose={function (): void {
            console.log('UpdateAppDrawerForm 表单: Event=onClose');
            handleShowAppTypeModal(false);
          }}
        />

        <ShowHostsListModal
          onChoose={async (value) => {
            console.log('AddAppWizardForm 表单: Event=ShowHostsListModal.onChoose,value =', value);
            handleShowHostListModal(false);
            handleHostname(value.hostname);
            handleIP(value.ip);
          }}
          onVisibleChange={(visible) => {
            if (visible) {
              console.log('AddAppWizardForm 表单: Event=onVisibleChange -> 显示ShowHostsListModal');
            } else {
              console.log(
                'AddAppWizardForm 表单: Event=onVisibleChange -> 关闭ShowHostsListModall',
              );
            }
            handleShowHostListModal(visible);
          }}
          showAppTypeModalVisible={showHostListModal}
          onClose={function (): void {
            console.log('AddAppWizardForm 表单: Event=ShowHostsListModal.onClose');
            handleShowHostListModal(false);
          }}
        />
      </Form.Provider>
    </>
  );
};

export default AppWizardModal;
